<template>
	<view>
		<!--   一条消息 -->
		<view  class="msgBox flex flex justify-start align-center m-3 p-3"  @click="goChat(item.talk_id[0]._id)"
		style="background-color: #ebdff7; border-radius: 15rpx;" v-if="item.chatList.length!=0"
		v-for="item in chatList">
			<!-- 头像 -->
			<view class="avatar" style="width: 100rpx; height: 100rpx; border-radius: 100rpx; overflow: hidden; border: 2px solid #b987ff;">
				<image :src="item.talk_id[0].avater" style="width: 100%;"
					mode="widthFix">
				</image>
			</view>
			 <view class="rightBox flex flex-column ml-3" style="width: 75%;" >
			 	<view class="top flex justify-between align-center mb-1">
			 		<view class="nickname" style="font-weight: bold; font-size: 35rpx; color:#4c1d95;">
			 			{{item.talk_id[0].nickname}}
			 		</view>
					<view class="time" style="font-size: 28rpx; color:#4c1d95;">
						<uni-dateformat :date="item.chatList[item.chatList.length - 1].publish_time" format="M/dd hh:mm" :threshold="[60000, 3600000]"></uni-dateformat>
					</view>
			 	</view>
				<view class="bottom" style="font-size: 32rpx; color: #4c1d95; overflow: hidden; white-space: nowrap;text-overflow: ellipsis;">
					{{item.chatList[item.chatList.length - 1].text}}
				</view>
			 </view>
		</view>
		
		
		
		
	</view>
</template>

<script>
import list from '../../uni_modules/uview-ui/libs/config/props/list';

	const db = uniCloud.database()
	const dbcmd = db.command
	export default {
		data() {
			return {
				userInfo:{},
				chatList:[]
			};
		},
	  async	onPullDownRefresh()
		{
			
			uni.showLoading({
				
			})
		   await this.getMsgList()
			uni.stopPullDownRefresh()
		},
	  async	onLoad() {
		  uni.showLoading({
		  	
		  })
		await uni.getStorage({
			key: 'jiajiao_demo_account',
			success: res => {
				this.userInfo = res.data
			}
		})
		 	this.getMsgList()
		},
		methods:{
		 async getMsgList()
			{
				this.chatList = []
				let listTemp = []
				let talkTemp = db.collection('jiajiao_users').field('_id,avater,nickname').getTemp()
				let chatTemp = db.collection('chatHistory').where(dbcmd.or({
				me_id: this.userInfo._id
			}, {
				talk_id: this.userInfo._id
			}, )).getTemp()
			  await	db.collection(chatTemp,talkTemp).get().then(res=>{
				  let arr = res.result.data
				  
					for(let i = 0; i < arr.length;i++) {	
						if(arr[i].me_id==this.userInfo._id)
						{
							if(i==0)
							arr[i].chatList.push(...arr[i+1].chatList)
							else
							arr[i].chatList.push(...arr[i-1].chatList)
							
							arr[i].chatList.sort((a,b)=> a.publish_time - b.publish_time)
							listTemp.push(arr[i])
						}
					}
				})
				
				this.chatList = listTemp
				
				uni.hideLoading()
			},
			
			goChat(id)
			{
				uni.navigateTo({
					url:`/pages/chat/chat?id=${id}`
				})
			}
		}
		
	}
</script>

<style lang="scss">
page{
	background-color: #f6eefe;
}
</style>
